import { createRouter, createWebHistory } from 'vue-router'
import ChatContainer from "@/views/Chat/ChatContainer.vue";
import AuthContainer from "@/views/Login/AuthContainer.vue";

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'Login',
        component: AuthContainer
    },
    {
        path: '/chat',
        name: 'Chat',
        component: ChatContainer,
        meta: { requiresAuth: true } // 需要登录才能访问
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫 - 检查登录状态
router.beforeEach((to, from, next) => {
    const isAuthenticated = localStorage.getItem('token')

    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login')
    } else if ((to.path === '/login' || to.path === '/register') && isAuthenticated) {
        next('/chat')
    } else {
        next()
    }
})

export default router
